package com.fanrenqiji.modules.sys.security;

import com.fanrenqiji.modules.sys.dao.UserDao;
import com.fanrenqiji.modules.sys.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年1月21日 下午4:56:32
 * @description 重写表单验证（包含验证码）过滤类
 */
@Service
public class FormAuthenticationFilter extends
		org.apache.shiro.web.filter.authc.FormAuthenticationFilter {
	
	
	@Autowired
	UserDao userDao;

	public static final String DEFAULT_CAPTCHA_PARAM = "validateCode";

	private String captchaParam = DEFAULT_CAPTCHA_PARAM;
	
	/**
	 * 自定义shiro登陆验证错误消息
	 */
	
	public static final String AUTHENTICATION_ERROR_MESSAGE = "authenticationErrorMessage";
	
	private  String errorMessage = "";
	
	


	public String getCaptchaParam() {
		return captchaParam;
	}

	protected String getCaptcha(ServletRequest request) {
		return WebUtils.getCleanParam(request, getCaptchaParam());
	}


	/**
	 * 为登录的用户创建token返回身份验证对象
	 */
	protected UsernamePasswordToken createToken(ServletRequest request,
			ServletResponse response) {
		String username = getUsername(request);
		String password = getPassword(request);
		String userstate ="";
		User user = userDao.findByLoginName(username);
		if(user!=null){
			 userstate = user.getUserState();
		}
		
		if (password == null) {
			password = "";
		}
		boolean rememberMe = isRememberMe(request);
		String host = getHost(request);
		String captcha = getCaptcha(request);
		return new UsernamePasswordToken(username, password.toCharArray(),
				rememberMe, host, captcha, userstate);
	}
	
	
	

    /**
     * 重写父类AuthenticatingFilter  中的executeLogin 方法，加入对用户状态的判断
     */

    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
    	UsernamePasswordToken token = createToken(request, response);
        //AuthenticationToken token = createToken(request, response);
        if (token == null) {
            String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " +
                    "must be created in order to execute a login attempt.";
            throw new IllegalStateException(msg);
        }
        try {
        	errorMessage ="";
        	if(token.getUserstate()!=null && token.getUserstate().equals("INACTIVE")){
        		errorMessage= "该用户已被禁用！请联系管理员";
        		AuthenticationException e = new AuthenticationException();
        		return onLoginFailure(token, e, request, response);
        	}
            Subject subject = getSubject(request, response);
            subject.login(token);
            return onLoginSuccess(token, subject, request, response);
        } catch (AuthenticationException e) {
            return onLoginFailure(token, e, request, response);
        }
    }
    
    
    protected boolean onLoginFailure(AuthenticationToken token,
    		AuthenticationException e, ServletRequest request,
    		ServletResponse response) {
    		boolean result = super.onLoginFailure(token, e, request, response);
    		//激活的用户才验证其他信息
    		if(StringUtils.isBlank(errorMessage)){
    			 errorMessage = "用户名或者密码错误,请重试";
        		if (e instanceof CaptchaException) {
        		errorMessage = "验证码输入错误,请重试";
        		}
    		}
    		request.setAttribute(AUTHENTICATION_ERROR_MESSAGE, errorMessage);
    	
    		return result;
    		}

    
}
